<template>
  <div class="cart">
    <div class="top" style="margin-top: 30px">
      <el-row>
        <el-col :span="3">
          <el-space style="height: 100%" :alignment="center">
            <span class="text_1">购物车:</span>
            <span class="text_1">{{ cartNum }} 种商品</span>
          </el-space>
        </el-col>
        <!-- <el-col :span="6" :offset="1">
          <el-input v-model="cartQuery" placeholder="搜索购物车的商品" class="input-with-select">
            <template #append>
              <el-button @click="query">
                <Search style="width: 1em; height: 1em" />
              </el-button>
            </template>
          </el-input>
        </el-col> -->
      </el-row>
    </div>
    <!-- @selection-change="handleSelectionChange" -->
    <el-table :data="tableData" style="width: 100%" ref="ref" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" />
      <el-table-column prop="image" label="商品" width="380">
        <template #default="scope">
          <el-space>
            <el-image :src="scope.row.image" style="width: 100px"></el-image>
            <span>{{ scope.row.storeName }}</span>
          </el-space>
        </template>
      </el-table-column>
      <el-table-column prop="vipPrice" label="单价" width="180" />
      <el-table-column prop="cartNum" label="数量">
        <template #default="scope">
          <el-input-number v-model="scope.row.cartNum" :min="1" @change="cartNumChange(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-space :size="6">
            <el-link :underline="false" @click="collection(scope.row)">移入收藏</el-link>
            <el-link :underline="false" @click="del(scope.row)">删除</el-link>
          </el-space>
        </template>
      </el-table-column>
    </el-table>
    <div class="bottom_cart">
      <el-space :size="12" alignment="center" style="width: 300px; height: 100%">
        <el-checkbox style="margin-left: 10px" v-model="checked1" @change="selectHanfle()" label="全选" size="large" />
        <!-- <el-link @click="allColl" v-show="is_show > 0">批量移入收藏夹</el-link> -->
        <!-- <el-link v-show="is_show">批量删除</el-link> -->
      </el-space>

      <el-space alignment="center" style="height: 100%" class="millde_b">
        <el-space v-show="is_show > 0" style="height: 100%; margin-right: 20px" alignment="center" :size="4">
          <span style="font-size: 12px; color: #666; font-family: PingFangSC-Medium">已选</span>
          <span style="font-size: 14px; color: #b8333c; font-family: PingFangSC-Medium">{{ selectedNum }}</span>
          <span style="font-size: 12px; color: #666; font-family: PingFangSC-Medium">件商品</span>
        </el-space>

        <el-space v-show="is_show > 0" style="height: 100%" alignment="center">
          <span style="font-size: 12px; color: #666; font-family: PingFangSC-Medium; margin-right: 10px">合计（不含运费）:</span>
        </el-space>

        <el-space v-show="is_show > 0" style="height: 100%" alignment="center" :size="2">
          <span style="font-size: 12px; font-weight: 600; color: #b8333c; font-family: PingFangSC-Medium">￥</span>
          <span style="font-size: 24px; font-weight: 600; line-height: 28px; color: #b8333c; font-family: PingFangSC-Medium; position: relative; top: -4px">{{ firstPrice }}</span>
          <!-- <span style="font-size: 12px; font-weight: 600; color: #b8333c; font-family: PingFangSC-Medium">.{{ lastPrice }}</span> -->
        </el-space>
      </el-space>

      <el-button style="position: absolute; right: 0; height: 100%; width: 112px; font-size: 20px; font-weight: 500" type="danger" @click="save" :disabled="is_show <= 0">去结算</el-button>
    </div>
  </div>
  <Sub v-model:visible="subVisible" @done="done" />
</template>

<script>
// import qs from 'qs'
import { Search } from '@element-plus/icons-vue'
import Sub from '@/components/submit'
export default {
  name: 'cart',
  components: {
    Search,
    Sub,
  },
  data() {
    return {
      tableData: [],
      checked1: false,
      // 查询内容
      cartQuery: '',
      is_show: 0,
      cartNum: 0,
      // 总价
      priceAll: 0,
      firstPrice: null,
      lastPrice: '00',
      // 已选
      selectedNum: 0,
      page: 1,
      // 提交后的弹窗
      subVisible: false,
    }
  },
  created() {
    // 获取列表
    this.getList()
  },
  methods: {
    selectHanfle(e) {
      if (e === false) {
        this.$refs.ref.clearSelection()
      } else {
        this.$refs.ref.toggleAllSelection()
      }
    },
    handleSelectionChange(row) {
      let i = []
      row.forEach((ele) => {
        i.push(ele.id)
      })
      this.tableData.forEach((item) => {
        if (i.indexOf(item.id) !== -1) {
          item.isSelect = true
        } else {
          item.isSelect = false
        }
      })

      /* 左下角的全选是否是选中 */
      if (row.length === this.tableData.length) {
        this.checked1 = true
      } else {
        this.checked1 = false
      }

      let flog = 0
      let price = 0
      this.selectedNum = 0
      this.tableData.forEach((item) => {
        if (item.isSelect === true) {
          flog += 1
          /* 计算价格和数量 */
          price += +item.vipPrice * item.cartNum
          this.selectedNum += item.cartNum
        }
      })
      this.firstPrice = Math.round(price * 10) / 10
      this.is_show = flog
    },
    handleCurrent(e, r) {
      console.log(e, r)
    },
    slelctAll() {
      console.log(123)
    },
    // 获取购物车列表
    getList() {
      this.$http
        .get('cart/list', {
          params: {
            isValid: 'true',
            limit: 20,
            page: this.page,
          },
        })
        .then((res) => {
          if (res.data.code === 200) {
            this.tableData = res.data.data.list
            this.cartNum = res.data.data.total
            console.log(res.data.data)
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch((e) => {
          this.$message.error(e.message)
        })
    },
    // 收藏
    collection(row) {
      this.$http
        .post('collect/add', {
          id: row.id,
          category: 'store',
        })
        .then((res) => {
          if (res.data.code === 200) {
            this.$message.success('收藏成功')
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch((e) => {
          this.$message.error(e.message)
        })
    },
    // 删除
    del(row) {
      this.$http
        .post('cart/delete?ids=' + row.id)
        .then((res) => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message)
            this.getList()
            this.$http
              .get('cart/count', {
                params: {
                  numType: true,
                  type: 'total',
                },
              })
              .then((res) => {
                if (res.data.code === 200) {
                  console.log(res.data.data)
                  this.setSessionItem('cartNum', res.data.data.count)
                } else {
                  this.$message.error(res.data.message)
                }
              })
              .catch((e) => {
                this.$message.error(e.message)
              })
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch((e) => {
          this.$message.error(e.message)
        })
    },
    /* 修改数量 */
    cartNumChange(row) {
      row.id = +row.id
      this.$http
        .post('cart/resetcart', { id: row.id, productId: row.productId, unique: row.productAttrUnique, num: row.cartNum })
        .then((res) => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message)
            this.getList()
          }
        })
        .catch((e) => {
          this.$message.error(e.message)
        })
    },
    // 结算
    save() {
      // 获取收货地址
      this.$http
        .get('address/default')
        .then((res) => {
          if (res.data.code === 200) {
            const addressId = res.data.data.id
            const data = {
              addressId,
              preOrderType: 'shoppingCart',
              remark: '',
              orderDetails: [],
            }
            this.tableData.forEach((item) => {
              if (item.isSelect === true) {
                data.orderDetails.push({
                  shoppingCartId: item.id,
                })
              }
            })
            this.$http
              .post('order/pre/UnifiedOrder', data)
              .then((res) => {
                if (res.data.code === 200) {
                  this.$message({
                    message: '订单已提交，请联系客服',
                    type: 'success',
                    duration: 10000,
                  })
                  this.getList()
                } else {
                  this.$message.error(res.data.message)
                }
              })
              .catch((e) => {
                this.$message.error(e.message)
              })
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch((e) => {
          this.$message.error(e.message)
        })
    },
    done() {
      this.subVisible = false
    },
  },
}
</script>

<style scoped lang="scss">
.cart {
  @include margin(1200px);
  .bottom_cart {
    width: 100%;
    border: 1px solid #e9e9e9;
    margin-top: 60px;
    height: 50px;
    box-sizing: border-box;
    position: relative;
    display: flex;
    .millde_b {
      position: absolute;
      right: 130px;
    }
  }
  .top {
    .text_1 {
      font-weight: 700;
      font-size: 16px;
      color: #1a1a1a;
    }
  }
  .el-table {
    border: 1px solid #e6e8ea;
    margin-top: 20px;
  }
}
</style>
